package com.itwk.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itwk.common.constant.ProductConstant;
import com.itwk.common.utils.PageUtils;
import com.itwk.common.utils.Query;
import com.itwk.gulimall.product.dao.*;
import com.itwk.gulimall.product.entity.*;
import com.itwk.gulimall.product.service.PmsAttrService;
import com.itwk.gulimall.product.service.PmsProductAttrValueService;
import com.itwk.gulimall.product.vo.AttrResponse;
import com.itwk.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("pmsAttrService")
public class PmsAttrServiceImpl extends ServiceImpl<PmsAttrDao, PmsAttrEntity> implements PmsAttrService {
    @Autowired
    private PmsAttrAttrgroupRelationDao attrgroupRelationDao;  //注入关联关系表的dao
    @Autowired
    private PmsCategoryDao categoryDao; //注入分类dao关联查询分类名
    @Autowired
    private PmsAttrGroupDao groupDao; //注入分组dao关联查询分组名
    @Autowired
    private PmsProductAttrValueService productAttrValueService; //查询spu的规格参数

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsAttrEntity> page = this.page(
                new Query<PmsAttrEntity>().getPage(params),
                new QueryWrapper<PmsAttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttrRelation(AttrVo attrVo) {
         //先保存Attr属性
        PmsAttrEntity pmsAttrEntity = new PmsAttrEntity();
        BeanUtils.copyProperties(attrVo, pmsAttrEntity);
        baseMapper.insert(pmsAttrEntity);
        //如果属性为基本属性再保存关联属性与属性组的关联关系
        if(attrVo.getAttrType()== ProductConstant.ATTR_TYPE_BASE.getCode()){
            PmsAttrAttrgroupRelationEntity entity = new PmsAttrAttrgroupRelationEntity();
            entity.setAttrId(pmsAttrEntity.getAttrId());
            entity.setAttrGroupId(attrVo.getAttrGroupId());
            attrgroupRelationDao.insert(entity);
        }

    }

    @Override
    public PageUtils attrRelationList(Map<String, Object> params, Long catelogId, String attrType) {
        //判断是销售属性还是基本属性 属性类型[0-销售属性，1-基本属性] 需要根据情况拼接条件
        String key = (String) params.get("key"); //取出检索条件
        boolean type = "sale".equals(attrType);//取出是否为销售属性
        QueryWrapper<PmsAttrEntity> queryWrapper = new QueryWrapper<PmsAttrEntity>().eq("attr_type", type?ProductConstant.ATTR_TYPE_SALE.getCode():ProductConstant.ATTR_TYPE_BASE.getCode());
        if(!StringUtils.isEmpty(key)){
            queryWrapper.eq("attr_id",key).or().like("attr_name",key);
        }

        if(catelogId!=0){   //判断是否有分类选择
            queryWrapper.and(warpper->{
                warpper.eq("catelog_id", catelogId);
            });
        }

        //先获取出全部属性，再关联查询扩展返回字段
        IPage<PmsAttrEntity> page = baseMapper.selectPage(new Query<PmsAttrEntity>().getPage(params), queryWrapper);
        //取出查询的记录进行字段扩展
        List<PmsAttrEntity> records = page.getRecords();

        //流式遍历
        List<AttrResponse> attrResponses = records.stream().map(attr -> {
            //通过关联表获取到分组id
            PmsAttrAttrgroupRelationEntity entity = attrgroupRelationDao.selectOne(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            //构建新的返回结果
            AttrResponse attrResponse = new AttrResponse();
            BeanUtils.copyProperties(attr, attrResponse);
             PmsCategoryEntity pmsCategoryEntity = categoryDao.selectById(attr.getCatelogId());
             attrResponse.setCatelogName(pmsCategoryEntity.getName());
             if(type){
                 //如果为销售属性直接返回，不用查询绑定分组信息
                 return attrResponse;
             }
             if(entity!=null&&entity.getAttrGroupId()!=null){
                 //查询分组名
                 PmsAttrGroupEntity pmsAttrGroupEntity = groupDao.selectById(entity.getAttrGroupId());
                 attrResponse.setGroupName(pmsAttrGroupEntity.getAttrGroupName());
             }

            return attrResponse;

        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);

        pageUtils.setList(attrResponses);

        return pageUtils;
    }

    @Override
    public AttrResponse getAttrResponse(Long attrId) {
        PmsAttrEntity pmsAttrEntity = baseMapper.selectById(attrId);//查询到对应的属性
        AttrResponse attrResponse = new AttrResponse();
        BeanUtils.copyProperties(pmsAttrEntity,attrResponse );
        //关联查询分类信息和分组信息
        PmsAttrAttrgroupRelationEntity relation = attrgroupRelationDao.selectOne(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", attrId));//查询属性属性组关联表

        if(relation!=null){
            attrResponse.setAttrGroupId(relation.getAttrGroupId());  //设置分组id
        }
        //调用递归获取完整路径
        ArrayList<Long> paths = new ArrayList<>();
        List<Long> catelogPaths = getCatelogPath(pmsAttrEntity.getCatelogId(), paths);
        Collections.reverse(catelogPaths); //倒叙
        Long[]  catelogPath= catelogPaths.toArray(new Long[0]);//转换数组

        attrResponse.setCatelogPath(catelogPath);


        return attrResponse;
    }

    //递归查询分类的完整路径
    private List<Long> getCatelogPath(Long catId, List<Long> paths){
        paths.add(catId);
        PmsCategoryEntity categoryEntity = categoryDao.selectById(catId);
        if(categoryEntity.getParentCid()!=0){  //父节点还有父节点
            getCatelogPath(categoryEntity.getParentCid(),paths);
        }

        return  paths;

    }

    @Override  //修改属性参数
    public void updateAttrRelation(AttrVo attrVo) {
        PmsAttrEntity pmsAttrEntity = new PmsAttrEntity();
        BeanUtils.copyProperties(attrVo, pmsAttrEntity);
        baseMapper.updateById(pmsAttrEntity);  //修改属性参数
        //关联修改，关联修改时要判断是新增关联关系还是修改
        Integer count = attrgroupRelationDao.selectCount(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
        PmsAttrAttrgroupRelationEntity relationEntity = new PmsAttrAttrgroupRelationEntity();

        if(count>0){
            //修改关联关系
            if(attrVo.getAttrGroupId()!=null){
                relationEntity.setAttrGroupId(attrVo.getAttrGroupId());  //修改分组信息
                attrgroupRelationDao.update(relationEntity,new UpdateWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            }


        }else{
            //新增关联关系
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());  //修改分组信息
            relationEntity.setAttrId(attrVo.getAttrId());
            attrgroupRelationDao.insert(relationEntity);
        }

    }

    @Override   // 修改spu的规格参数的回显
    public List<PmsProductAttrValueEntity> getSpuBaseAttr(Long spuId) {
        List<PmsProductAttrValueEntity> entities = productAttrValueService.list(new QueryWrapper<PmsProductAttrValueEntity>().eq("spu_id", spuId));

        return entities;
    }

    @Override //修改spu修改规格后提交的参数
    public void updateSpuBaseAttr(List<PmsProductAttrValueEntity> productAttrValueEntities, Long spuId) {
         //这里情况较为复杂，如果之前属性值为空其实是插入操作，有值为修改操作，但其实此处插入实际也为update 将null 值置为有值，这里可以直接采用修改操作，也可以先删除该spu下的基本属性再插入操作
        productAttrValueService.remove(new QueryWrapper<PmsProductAttrValueEntity>().eq("spu_id", spuId));
        //为每个属性赋上spu_id
        List<PmsProductAttrValueEntity> collect = productAttrValueEntities.stream().map(entity -> {
            entity.setSpuId(spuId);
            return entity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
    }


}
